﻿using System;
using System.Windows;
using System.Windows.Threading;
using RFS.BizLogic;
using RFS.BizLogic.Sys;
using RFS.BizLogic.utils;
using RFS.WPF.StartUp;
using RFS.WPF.utils;
using RFS.WPF.Views;

namespace RFS.WPF
{

    public partial class App:System.Windows.Application
    {
        private IAntiObject _antiObject;
        ILog _log;
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Handle exceptions in the UI thread
            this.DispatcherUnhandledException += OnDispatcherUnhandledException;

            // Handle exceptions in non-UI threads
            AppDomain.CurrentDomain.UnhandledException += OnAppDomainUnhandledException;
            
            
             _antiObject= ViewStarter.Start()  ;
             _log = _antiObject.Get<ILog>();
             var vm = _antiObject.Get<SysVm>();
            var mainWindow = new MainWindow(vm) ;
            // var mainWindow = new FaHuoDuizhangView( ) ;
            mainWindow.Show();
        }


        private int idx = 0;
        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            if (idx++ < 1)
            {
                e.Handled = true;

                return;
            }
            
                // MessageBox.Show("原因: " + e.Exception.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);

            
            // Log the exception, show a message to the user, etc.
            var msg=$"错误：{e.Exception.Message}"  ;

            _log?.Err(new Exception(msg));
            // Optionally set e.Handled to true to prevent the application from crashing
            e.Handled = true;
        }

        private void OnAppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // Handle non-UI thread exceptions here
            if (e.ExceptionObject is Exception ex)
            {
                // Log the exception or take necessary actions
                // MessageBox.Show("原因: " + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            
                _log?.Err(ex);
            }
            // Environment.Exit(-1);
            
            // The application will exit if this is not handled, as the runtime considers this a fatal error
        }

        protected override void OnExit(ExitEventArgs e)
        {
            // Optional: Unsubscribe from events when the application exits
            this.DispatcherUnhandledException -= OnDispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException -= OnAppDomainUnhandledException;

            
            _antiObject.Get<ISys>().Exist();
            base.OnExit(e);
        }
    }
}